//
//  JGDetailViewController.m
//  JGMeiTuanHD
//
//  Created by JJetGu on 15/9/27.
//  Copyright (c) 2015年 Free. All rights reserved.
//

#import "JGDetailViewController.h"
#import "JGConst.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "JGCenterLineLabel.h"
#import "JGDeal.h"
#import "UIImageView+WebCache.h"
#import "JGDealDBTool.h"
#import "JGDPRequestTool.h"
#import "JGRestrictions.h"
#import "JGDealDBTool.h"

//阿里支付
#import "AlixLibService.h"
#import "AlixPayOrder.h"
#import "DataSigner.h"
#import "PartnerConfig.h"

@interface JGDetailViewController () <UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingView;

@property (weak, nonatomic) IBOutlet UIImageView *contentImage;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;

@property (weak, nonatomic) IBOutlet UILabel *currentMoney;
@property (weak, nonatomic) IBOutlet JGCenterLineLabel *originMoney;
/** 收藏按钮*/
@property (weak, nonatomic) IBOutlet UIButton *collectButton;

@property (weak, nonatomic) IBOutlet UIButton *refundableAnyTimeButton;
@property (weak, nonatomic) IBOutlet UIButton *leftTimeButton;
@property (weak, nonatomic) IBOutlet UIButton *refundableExpireButton;
@property (weak, nonatomic) IBOutlet UIButton *saleNumberButton;

@property (nonatomic ,strong)JGDeal *tempDeal;

@end

@implementation JGDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
     self.view.backgroundColor = JGGlobalBg;
    
    // 存储浏览记录
    [JGDealDBTool addRecentDeal:self.deal];
    
    self.tempDeal = self.deal;
    
    // 加载网页
    self.webView.hidden = YES;
    self.webView.delegate = self;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.deal.deal_h5_url]]];
    
    // 设置基本信息
    [self.contentImage sd_setImageWithURL:[NSURL URLWithString:self.deal.image_url] placeholderImage:[UIImage imageNamed:@"placeholder_deal"]];
    self.titleLabel.text = self.deal.title;
    self.descLabel.text = self.deal.desc;
    // 现价
    self.currentMoney.text = [NSString stringWithFormat:@"¥ %@", self.deal.current_price];
    NSUInteger dotLoc = [self.currentMoney.text rangeOfString:@"."].location;
    if (dotLoc != NSNotFound) {
        // 超过2位小数
        if (self.currentMoney.text.length - dotLoc > 3) {
            self.currentMoney.text = [self.currentMoney.text substringToIndex:dotLoc + 3];
        }
    }
    // 原价
    self.originMoney.text = [NSString stringWithFormat:@"¥ %@", self.deal.list_price];
    
    //设置剩余时间
    [self.leftTimeButton setTitle:[self getLeftTime] forState:UIControlStateNormal];
    
    //已售出数量
    [self.saleNumberButton setTitle:[NSString stringWithFormat:@"已售出 %d", self.deal.purchase_count] forState:UIControlStateNormal];
    
    // 设置收藏状态
    self.collectButton.selected = [JGDealDBTool isCollected:self.deal];
    

#warning mark - 要再发一次请求
     // 再一次发送请求获得更详细的团购数据
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"deal_id"] = self.deal.deal_id;
    __weak typeof(self) weakSelf = self;
    [[JGDPRequestTool sharedAPITool] request:@"v1/deal/get_single_deal" params:params success:^(id json) {
        //重新赋值模型
        weakSelf.deal = [JGDeal objectWithKeyValues:[json[@"deals"] firstObject]];
        //用原来的image_url---------
        weakSelf.deal.image_url = self.tempDeal.image_url;
        
        // 设置退款信息
        weakSelf.refundableAnyTimeButton.selected = weakSelf.deal.restrictions.is_refundable;
        weakSelf.refundableExpireButton.selected = weakSelf.deal.restrictions.is_refundable;
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络繁忙,请稍后再试" toView:weakSelf.view];
    }];
}

/**
 * 获得剩余时间
 */
-(NSString *)getLeftTime
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSDate *dead = [fmt dateFromString:self.deal.purchase_deadline];
    //在原来的时间上追加一天
    dead = [dead dateByAddingTimeInterval:24 * 60 * 60];
    
    //现在的时间
    NSDate *now = [NSDate date];
    
    //作比较
    NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
    NSDateComponents *cmps = [[NSCalendar currentCalendar] components:unit fromDate:now toDate:dead options:0];
    if (cmps.day > 365)
    {
        return @"一年内不过期";
    }
    else
    {
        return [NSString stringWithFormat:@"%ld天%ld小时%ld分钟", (long)cmps.day, (long)cmps.hour, (long)cmps.minute];
    }
    
}

/**
 *  返回控制器支持的方向
 */
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if ([webView.request.URL.absoluteString isEqualToString:self.deal.deal_h5_url]) {
        // 旧的HTML5页面加载完毕
        NSString *ID = [self.deal.deal_id substringFromIndex:[self.deal.deal_id rangeOfString:@"-"].location + 1];
        NSString *urlStr = [NSString stringWithFormat:@"http://lite.m.dianping.com/group/deal/moreinfo/%@", ID];
         [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    }
    else // 详情页面加载完毕
    {
        // 用来拼接所有的JS
        NSMutableString *js = [NSMutableString string];
        // 删除header
        [js appendString:@"var header = document.getElementsByTagName('header')[0];"];
        [js appendString:@"header.parentNode.removeChild(header);"];
        // 删除顶部的购买
        [js appendString:@"var box = document.getElementsByClassName('cost-box')[0];"];
        [js appendString:@"box.parentNode.removeChild(box);"];
        // 删除底部的购买
        [js appendString:@"var buyNow = document.getElementsByClassName('buy-now')[0];"];
        [js appendString:@"buyNow.parentNode.removeChild(buyNow);"];
        
        // 利用webView执行JS
        [webView stringByEvaluatingJavaScriptFromString:js];
        
        // 显示webView
        webView.hidden = NO;
        // 隐藏正在加载
        [self.loadingView stopAnimating];
        
        // 获得页面
        //        NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].outerHTML;"];
    }
}

#pragma mark - 返回按钮
- (IBAction)backTo:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 立即购买
- (IBAction)buyAction:(id)sender
{
    //跳转到阿里支付网站
    //    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.deal.deal_url]];
    
    //手动集成支付宝
    // 1.生成订单信息
    // 订单信息 == order == [order description]
    AlixPayOrder *order = [[AlixPayOrder alloc] init];
    order.productName = self.deal.title;
    order.productDescription = self.deal.desc;
    order.partner = PartnerID;
    order.seller = SellerID;
    order.amount = [self.deal.current_price description];
    
    // 2.签名加密
    id<DataSigner> signer = CreateRSADataSigner(PartnerPrivKey);
    // 签名信息 == signedString
    NSString *signedString = [signer signString:[order description]];
    
    // 3.利用订单信息、签名信息、签名类型生成一个订单字符串
    NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                             [order description], signedString, @"RSA"];
    
    // 4.打开客户端,进行支付(商品名称,商品价格,商户信息)
    [AlixLibService payOrder:orderString AndScheme:@"jgtuangou" seletor:@selector(getResult:) target:self];
    
}

#pragma mark - 打开网页版时，支付的结果才会回调合格发方法
- (void)getResult:(NSString *)result
{
    
}


#pragma mark - 收藏按钮
- (IBAction)collectAction:(id)sender
{
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[JGCollectDealKey] = self.deal;
    
    if (self.collectButton.isSelected) {
        // 取消收藏
        //从数据库移除
        [JGDealDBTool removeCollectDeal:self.deal];
        [MBProgressHUD showSuccess:@"取消收藏成功" toView:self.view];
        
    } else {
        // 收藏
        [JGDealDBTool addCollectDeal:self.deal];
        [MBProgressHUD showSuccess:@"收藏成功" toView:self.view];
    }
    
    // 按钮的选中取反
    self.collectButton.selected = !self.collectButton.isSelected;
    
    // 发出通知 -- 刷新收藏页面
    [JGNotificationCenter postNotificationName:JGCollectStateDidChangeNotification object:nil userInfo:info];
}

#pragma mark - 分享按钮
- (IBAction)shareAction:(id)sender
{
    
}

@end
